﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace PressureDiary
{
    public partial class DetailsPage : PhoneApplicationPage
    {

        private List<Measure> details = new List<Measure>();
        private int year;
        private int month;

        public DetailsPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string yearMonth = string.Empty;

            if (NavigationContext.QueryString.TryGetValue("key", out yearMonth))
            {
                string myData = yearMonth + "-" + "1";
                string[] pairs = yearMonth.Split('-');
                this.year = Convert.ToInt16(pairs[0]);
                this.month = Convert.ToInt16(pairs[1]);
                DateTime data = Convert.ToDateTime(myData);
                PageTitle.Text = data.ToString("MMMM") + " " + this.year;

                LoadMeasurementsData(this.year, this.month);
            }
            else
            {
                MessageBox.Show("Error loading data.", "ERROR", MessageBoxButton.OK);
            }
        }

        private void DeleteItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var menuItemGuid = ((MenuItem)sender).CommandParameter;

                if (MessageBox.Show("Do you really wanna delete this measure?", "Warning", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    using (MyDatabaseContext context = new MyDatabaseContext(MyDatabaseContext.ConnectionString))
                    {
                        Measure measure = context.Measures.Where(x => x.Id.ToString() == menuItemGuid).SingleOrDefault();
                        context.Measures.DeleteOnSubmit(measure);
                        context.SubmitChanges();
                    }
                }
                LoadMeasurementsData(this.year, this.month);
                UpdateApplicationTile(this.getAbsoluteLastMeasure());
            }
            catch (Exception)
            {
                MessageBox.Show("Error deleting item.", "ERROR", MessageBoxButton.OK);
            }
        }

        private void LoadMeasurementsData(int year, int month)
        {
            using (MyDatabaseContext context = new MyDatabaseContext(MyDatabaseContext.ConnectionString))
            {
                this.details = context.Measures.Where(x => x.Date.Value.Year == year && x.Date.Value.Month == month).ToList();
                this.details.Reverse();

                App.measuresInMonth = this.details.Where(x => x.Date.Value.Month == month).Count();
                // Come faccio a notificare la tile se cancello da qui?

                MeasurementListBox.ItemsSource = this.details;
            }
        }

        public void UpdateApplicationTile(Measure measure)
        {
            var appTile = ShellTile.ActiveTiles.First();

            if (appTile != null)
            {
                var standardTile = new StandardTileData
                {
                    Title = App.ApplicationName,
                    BackgroundImage = new Uri("Images/PressureDiaryIcon_173x173.png", UriKind.Relative),
                    Count = App.measuresInMonth, // ci metto il numero di misurazioni del mese in corso
                    BackTitle = App.ApplicationName,
                    //BackBackgroundImage = new Uri("Images/ApplicationTileIcon.jpg", UriKind.Relative),  
                    BackContent = "Last measure: " + "[" + measure.Systolic.ToString() + "/" + measure.Diastolic.ToString() + "]" + measure.Date.Value.ToShortDateString()
                };

                appTile.Update(standardTile);
            }
        }

        private Measure getAbsoluteLastMeasure()
        {
            List<Measure> last = new List<Measure>();
            using (MyDatabaseContext context = new MyDatabaseContext(MyDatabaseContext.ConnectionString))
            {
                last = context.Measures.ToList();
                last.Reverse();

                return last.First();
            }
        }

    }
}